﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using VO.Entities;

namespace VO.Business.Controllers
{
    public static class UsersController
    {
        public static List<User> GetUsers()
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.Users.ToList();
            }
        }

        public static User GetUser(int id)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.Users.Include("ClubsOwned").SingleOrDefault(p => p.Id == id);
            }
        }

        public static User GetUserByIdMembership(Guid idMembership)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.Users.SingleOrDefault(p => p.IdMembership == idMembership);
            }
        }

        public static bool SaveUser(User user, bool isnew)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                user.LastEditDate = DateTime.Now;

                try
                {
                    ctx.AttachTo("Users", user);
                    if (isnew)
                    {
                        user.CreatedDate = DateTime.Now;
                        user.Version = 0;
                    }
                    ctx.ObjectStateManager.ChangeObjectState(user, isnew ? EntityState.Added: EntityState.Modified);
                    
                    return ctx.SaveChanges() > 0;
                }
                catch(OptimisticConcurrencyException exOpt)
                {
                    ctx.Refresh(RefreshMode.ClientWins, user);
                    
                    return ctx.SaveChanges() > 0;
                }
                catch (Exception)
                {
                    throw;
                }                    
            }
        }
    }
}
